import os, uuid

db.define_table('catalog_folder',
                Field('root_id','reference catalog_folder'),
                Field('path'),
                Field('title'),
                Field('header','text'),
                Field('footer','text'),
                Field('pattern_ignore'),
                Field('pattern_group'),
                Field('comments','boolean',default=True))
db.define_table('tag',
                Field('name'),
                Field('root_id','reference catalog_folder'))
db.define_table('catalog_file',
                Field('root_id','reference catalog_folder'),
                Field('filename'),
                Field('md5'),
                Field('pattern'),
                Field('extension'),
                Field('size','decimal(20,0)'),
                Field('mtime','datetime'))

db.catalog_file.filename.represent=lambda f:A(os.path.basename(f),_href=settings.geturl % f[7:])

db.define_table('token',
                Field('owner','reference auth_user'),
                Field('uuid'),
                auth.signature)

if auth.user:
    auth.user.token_uuid=(db.token(owner=auth.user.id) or db.token.insert(owner=auth.user.id,uuid=str(uuid.uuid4()))).uuid

db.define_table('service',
                Field('owner','reference auth_user'),
                Field('link',requires=IS_URL()))

db.define_table('bookmark',
                Field('owner','reference auth_user'),
                Field('root_id'))

db.define_table('attribute',
                Field('catalog',db.catalog_file),
                Field('name'),
                Field('value','double'))

def getfile(name):
    return settings.geturl % name[8:]

def name(path):
    if path.endswith('/'): path=path[:-1]
    return os.path.basename(path)

def bytes(size):
    if size<10**3:
        return "%.1f B" % size
    if size<10**6:
        return "%.1f KB" % int(size/10**3)
    if size<10**9:
        return "%.1f MB" % int(size/10**6)
    if size<10**12:
        return "%.1f GB" % int(size/10**9)
    else:
        return "%.1f TB" % int(size/10**12)
